const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 使用绝对路径，确保在项目根目录
const projectRoot = process.cwd();
const avatarDir = path.join(projectRoot, 'uploads', 'images', 'avatars');

console.log('=== 上传配置信息 ===');
console.log('项目根目录:', projectRoot);
console.log('头像目录:', avatarDir);

// 确保目录存在
if (!fs.existsSync(avatarDir)) {
  fs.mkdirSync(avatarDir, { recursive: true });
  console.log('创建目录:', avatarDir);
}

// 测试目录可写性
try {
  const testFile = path.join(avatarDir, 'test-write.txt');
  fs.writeFileSync(testFile, 'test');
  fs.unlinkSync(testFile);
  console.log('目录可写: 是');
} catch (error) {
  console.log('目录可写: 否 -', error.message);
}

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, avatarDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const extension = path.extname(file.originalname) || '.jpg';
    const filename = 'avatar-' + uniqueSuffix + extension;
    console.log('生成文件名:', filename);
    cb(null, filename);
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 2 * 1024 * 1024
  },
  fileFilter: (req, file, cb) => {
    console.log('文件过滤:', file.originalname, '->', file.mimetype);
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  }
});

module.exports = upload;